package com.uinnova.product.eam.web.eam.mvc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.util.ControllerUtils;
import com.uinnova.product.eam.model.TechnologyStackDto;
import com.uinnova.product.eam.model.dto.EamDataSetClassDto;
import com.uinnova.product.eam.model.dto.EamTableFriendDto;
import com.uinnova.product.eam.service.ICIDataSetSvc;
import com.uinnova.product.vmdb.comm.doc.annotation.ModDesc;
import com.uinnova.product.vmdb.comm.doc.annotation.MvcDesc;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiInfo;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.cmdb.business.dataset.DataSetExeResultSheetPage;
import com.uino.bean.cmdb.business.dataset.FriendInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Validated
@RequestMapping("/eam/ciDataSet")
@MvcDesc(author = "guan", desc = "对象数据超市")
public class EamCiDataSetMvc {

    @Autowired
    private ICIDataSetSvc ciDataSetSvc;


    @ModDesc(desc = "通过数据超市查询指定CI关联的对象集合", pDesc = "数据集及起始CI", rDesc = "朋友圈信息", rType = FriendInfo.class)
    @RequestMapping("/queryFriendInfo")
    public void queryFriendInfo(@RequestParam(defaultValue = "DESIGN") LibType libType,
                                HttpServletRequest request, HttpServletResponse response, @RequestBody String body) {
        JSONObject paramJson = JSON.parseObject(body);
        BinaryUtils.checkEmpty(paramJson.getLong("dataSetId"), "dataSetId");
        BinaryUtils.checkEmpty(paramJson.getLong("ciId"), "ciId");
        long dataSetId = paramJson.getLong("dataSetId");
        long ciId = paramJson.getLong("ciId");
        FriendInfo result = ciDataSetSvc.queryFriendByStartCiId(libType, dataSetId, ciId);
        ControllerUtils.returnJson(request, response, result);
    }


    @ModDesc(desc = "通过数据超市查询指定CI关联的技术栈信息", pDesc = "数据集及起始CI", rDesc = "技术栈信息信息", rType = TechnologyStackDto.class)
    @RequestMapping("/queryTechnologyStack")
    public void queryTechnologyStack(@RequestParam(defaultValue = "DESIGN") LibType libType,
                                     HttpServletRequest request, HttpServletResponse response, @RequestBody String body) {
        JSONObject paramJson = JSON.parseObject(body);
        BinaryUtils.checkEmpty(paramJson.getLong("dataSetId"), "dataSetId");
        BinaryUtils.checkEmpty(paramJson.getLong("ciId"), "ciId");
        long dataSetId = paramJson.getLong("dataSetId");
        long ciId = paramJson.getLong("ciId");
        //TechnologyStackDto result = ciDataSetSvc.queryAppTechnologyStack(libType, dataSetId, ciId);
        List<CcCiInfo> componentList = ciDataSetSvc.queryRelatedCIByDataSet(libType, dataSetId, ciId);
        Collections.sort(componentList, (o1, o2) -> {
            if (o1.getAttrs().containsKey("所属技术层级")) {
                String o1Level = o1.getAttrs().get("所属技术层级");
                String o2Level = o2.getAttrs().get("所属技术层级");
                return o2Level.compareTo(o1Level);
            } else {
                return 1;
            }
        });
        List<CcCiInfo> realComponentList = ciDataSetSvc.queryRelatedListCIInfo(ciId, libType);
        Map<String, Map<String, Object>> resultMap = ciDataSetSvc.getResultMap(realComponentList, componentList);
        ControllerUtils.returnJson(request, response, resultMap);
    }
    @RequestMapping("/queryArchitectureDescription")
    public void queryArchitectureDescription(@RequestParam(defaultValue = "DESIGN") LibType libType,
                                             HttpServletRequest request, HttpServletResponse response,@RequestBody String body){
        JSONObject paramJson = JSON.parseObject(body);
        BinaryUtils.checkEmpty(paramJson.getLong("ciId"), "ciId");
        BinaryUtils.checkEmpty(paramJson.getLong("BFDataSetId"), "BFDataSetId");
        BinaryUtils.checkEmpty(paramJson.getLong("BPDataSetId"), "BPDataSetId");
        BinaryUtils.checkEmpty(paramJson.getLong("APFDataSetId"), "APFDataSetId");

        long ciId = paramJson.getLong("ciId");
        Long bfDataSetId = paramJson.getLong("BFDataSetId");
        Long bpDataSetId = paramJson.getLong("BPDataSetId");
        Long apfDataSetId = paramJson.getLong("APFDataSetId");

        List<CcCiInfo> BFComponentList = ciDataSetSvc.queryRelatedCIByDataSet(libType, bfDataSetId, ciId);
        List<CcCiInfo> BPComponentList = ciDataSetSvc.queryRelatedCIByDataSet(libType, bpDataSetId, ciId);
        List<CcCiInfo> APFComponentList = ciDataSetSvc.queryRelatedCIByDataSet(libType, apfDataSetId, ciId);

        Map<String,List<CcCiInfo>> resultMap = new HashMap<>();
        if(!BFComponentList.isEmpty()){
            resultMap.put("BF",BFComponentList);
        }
        if(!BPComponentList.isEmpty()){
            resultMap.put("BP",BPComponentList);
        }
        if(!APFComponentList.isEmpty()){
            resultMap.put("APF",APFComponentList);
        }
        ControllerUtils.returnJson(request, response, resultMap);
    }

    @ModDesc(desc = "通过数据超市查询指定CI关联的CI信息", pDesc = "数据集及起始CI", rDesc = "关联信息", rType = List.class)
    @RequestMapping("/queryRelatedCIByDataSet")
    public void queryRelatedCIByDataSet(@RequestParam(defaultValue = "DESIGN") LibType libType,
                                        HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject body) {
        BinaryUtils.checkEmpty(body.getLong("dataSetId"), "dataSetId");
        BinaryUtils.checkEmpty(body.getLong("ciId"), "ciId");
        long dataSetId = body.getLong("dataSetId");
        long ciId = body.getLong("ciId");
        List<CcCiInfo> result = ciDataSetSvc.queryRelatedCIByDataSet(libType, dataSetId, ciId);
        ControllerUtils.returnJson(request, response, result);
    }

    @ModDesc(desc = "通过数据集的名称获取到数据集信息", pDesc = "数据集名称", rDesc = "数据集对象", rType = JSONObject.class)
    @RequestMapping("/queryDataSetByName")
    public void queryDataSetByName(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject body) {
        BinaryUtils.checkEmpty(body.getString("name"), "name");
        String name = body.getString("name");
        String contextPath = request.getContextPath();
        JSONObject result = ciDataSetSvc.queryDataSetByName(name, contextPath);
        ControllerUtils.returnJson(request, response, result);
    }

    @ModDesc(desc = "通过数据超市查询指定CI关联的非功能指标信息", pDesc = "数据集及起始CI", rDesc = "关联信息", rType = List.class)
    @RequestMapping("/queryNonIndicatorsCIByDataSet")
    public void queryNonIndicatorsCIByDataSet(@RequestParam(defaultValue = "DESIGN") LibType libType,
                                              HttpServletRequest request, HttpServletResponse response,
                                              @RequestBody JSONObject body) {
        BinaryUtils.checkEmpty(body.getLong("dataSetId"), "dataSetId");
        BinaryUtils.checkEmpty(body.getLong("ciId"), "ciId");
        long dataSetId = body.getLong("dataSetId");
        long ciId = body.getLong("ciId");
        List<CcCiInfo> result = ciDataSetSvc.queryRelatedCIByDataSet(libType, dataSetId, ciId);
        HashMap<String, Map<String, Object>> resultMap = new HashMap<>();
        for (CcCiInfo ccCiInfo : result) {
            String oneLeveType = ccCiInfo.getAttrs().get("所属类型_一级");
            Map<String, Object> oneLevelMap = resultMap.computeIfAbsent(oneLeveType, k -> new HashMap<>());
            String twoLevelType = ccCiInfo.getAttrs().get("所属类型_二级");
            //解析二级所属类型，不存在直接存ciCode
            if (StringUtils.isNoneBlank(twoLevelType)) {
                Object o = oneLevelMap.computeIfAbsent(twoLevelType, k -> new HashMap<>());
                JSONObject twoLeveMap = JSONObject.parseObject(JSON.toJSONString(o));
                String ciCode = ccCiInfo.getCi().getCiCode();
                twoLeveMap.put(ciCode, ccCiInfo.getAttrs());
                oneLevelMap.put(twoLevelType, twoLeveMap);
                oneLevelMap.put("hasNextLevel", true);
            } else {
                String ciCode = ccCiInfo.getCi().getCiCode();
                oneLevelMap.put(ciCode, ccCiInfo.getAttrs());
                oneLevelMap.put("hasNextLevel", false);
            }
        }
        ControllerUtils.returnJson(request, response, resultMap);
    }

    @ModDesc(desc = "通过数据集的名称获取到数据集信息并返回根节点分类信息", pDesc = "数据集名称", rDesc = "数据集对象及根节点分类信息", rType = JSONObject.class)
    @RequestMapping("/queryDataSetByNames")
    public void queryDataSetByNames(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject body) {
        JSONArray jsonName = body.getJSONArray("names");
        List<String> names = null;
        if(!BinaryUtils.isEmpty(jsonName)){
            names = jsonName.toJavaList(String.class);
        }
        JSONArray jsonId = body.getJSONArray("ids");
        List<Long> ids = null;
        if(!BinaryUtils.isEmpty(jsonId)){
            ids = jsonId.toJavaList(Long.class);
        }
        String like = body.getString("like");
        List<EamDataSetClassDto> result = ciDataSetSvc.queryDataSetByNames(ids, names, like);
        ControllerUtils.returnJson(request, response, result);
    }

    @ModDesc(desc = "通过规则和入口查询关系呈现为表格", pDesc = "根节点id", rDesc = "关系数据集表格结构", rType = JSONObject.class)
    @PostMapping("/queryTableFriend")
    public void queryTableFriend(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody EamTableFriendDto body) {

        DataSetExeResultSheetPage result = ciDataSetSvc.queryTableFriend(body);
        ControllerUtils.returnJson(request, response, result);
    }

    @ModDesc(desc = "通过规则和入口批量查询关系呈现为表格", pDesc = "根节点id", rDesc = "关系数据集表格结构", rType = JSONObject.class)
    @PostMapping("/queryTableFriendList")
    public void queryTableFriendList(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody List<EamTableFriendDto> body) {

        List<DataSetExeResultSheetPage> result = ciDataSetSvc.queryTableFriendList(body);
        ControllerUtils.returnJson(request, response, result);
    }

    @ModDesc(desc = "应用系统全景分析-接口服务展示", pDesc = "关系id", rDesc = "服务对象信息", rType = JSONObject.class)
    @PostMapping("/serviceAnalysis")
    public void serviceAnalysis(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject body) {
        List<Long> rltIds = body.getJSONArray("id").toJavaList(Long.class);
        BinaryUtils.checkEmpty(rltIds, "rltId");
        Map<Long, List<CcCiInfo>> result = ciDataSetSvc.serviceAnalysis(rltIds);
        ControllerUtils.returnJson(request, response, result);
    }
}
